package com.inscream.app;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;


public class RecordActivity extends Activity implements View.OnClickListener{

    Button sendServer;
    ImageButton againMyRecord, startRecord, playRecord, stopRecord;

    private CountDownTimer countDownTimer;
    private final long startTime = 5 * 1000;
    private final long interval = 1 * 1000;
    private boolean timerHasStarted = false;

    public String newCreateFileName;
    private String outputFile = null;
    private MediaRecorder myAudioRecorder;
    private boolean isRunning;

    public ProgressDialog pDialog;
    RelativeLayout relativeLayout3;
    TabHost tabHost;

    EditText dialogHashText;
    ImageButton dialogSendButton;
    Dialog dialog;

    TextView recordSecond;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_record);

        countDownTimer = new MyCountDownTimer(startTime, interval);

        stopRecord = (ImageButton) findViewById(R.id.stopRecord);
        startRecord = (ImageButton) findViewById(R.id.startRecord);
        againMyRecord = (ImageButton) findViewById(R.id.AgainMyRecord);
        recordSecond = (TextView) findViewById(R.id.recordSecond);
        playRecord = (ImageButton) findViewById(R.id.playRecord);
        sendServer = (Button) findViewById(R.id.sendServer);
        newCreateFileName = RandomAlphaNumericString(12);
        relativeLayout3 = (RelativeLayout) findViewById(R.id.relativeLayout3);
        stopRecord.setEnabled(false);
        playRecord.setEnabled(false);
        outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/inscream"+newCreateFileName+".3gp";
        myAudioRecorder = new MediaRecorder();
        myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
        myAudioRecorder.setOutputFile(outputFile);

        sendServer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v){
                // custom dialog
                dialog = new Dialog(RecordActivity.this);
                dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
               dialog.setContentView(R.layout.custommodal);
                // set the custom dialog components - text, image and button
                dialog.show();
                dialogHashText = (EditText) dialog.findViewById(R.id.writeMessage);
                dialogSendButton = (ImageButton) dialog.findViewById(R.id.dialogSendButton);
                dialogSendButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                        pDialog = new ProgressDialog(RecordActivity.this);
                        pDialog.setMessage("Uploading, Wait a min...");
                        pDialog.setIndeterminate(false);
                        pDialog.setCancelable(true);
                        pDialog.show();
                        new Thread(new Runnable() {
                            public void run() {
                                UploadFile(newCreateFileName);
                            }
                        }).start();
                    }
                });
            }
        });
    }


    public class MyCountDownTimer extends CountDownTimer {
        public MyCountDownTimer(long startTime, long interval) {
            super(startTime, interval);
        }

        @Override
        public void onFinish() {
           // recordSecond.setText("Time's up!");
            recordSecond.setText("0");
            stopRecord.performClick();
            sendServer.performClick();
        }

        @Override
        public void onTick(long millisUntilFinished) {
            recordSecond.setText("" + millisUntilFinished / 1000);
        }
    }
        public String RandomAlphaNumericString(int size){
        String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        String newRetName = "";
        int length = chars.length();
        for (int i = 0; i < size; i++){
            newRetName += chars.split("")[ (int) (Math.random() * (length - 1)) ];
        }
        return newRetName;
    }

    public void UploadFile(String newCreateFileName){
        try {
            // Set your file path here
            FileInputStream fstrm = new FileInputStream(Environment.getExternalStorageDirectory().getAbsolutePath().toString()+"/inscream"+newCreateFileName+".3gp");
            String newMyFileName = newCreateFileName;
            // Set your server page url (and the file title/description)
            HttpFileUpload hfu = new HttpFileUpload("http://mehmetalp.com.tr/seslitwitter/submitrecord.php", "2", dialogHashText.getText().toString());
            hfu.Send_Now(fstrm, newMyFileName);
            pDialog.dismiss();
           // ((TabActivity) getParent()).getTabHost().setCurrentTab(2);
           // tabHost.setCurrentTab(0);

        } catch (FileNotFoundException e) {
           //  pDialog.dismiss();
        }
    }

    /////////////////////////////
    public void start(View view){
        recordSecond.setVisibility(View.VISIBLE);
        againMyRecord.setVisibility(View.VISIBLE);
        if (!timerHasStarted) {
            countDownTimer.start();
            timerHasStarted = true;
        } else {
            countDownTimer.cancel();
            timerHasStarted = false;
        }
        try {
            isRunning = true;
            startTimer();
            myAudioRecorder.prepare();
            myAudioRecorder.start();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        startRecord.setEnabled(false);
        stopRecord.setEnabled(true);
        Toast.makeText(getApplicationContext(), "Recording started", Toast.LENGTH_LONG).show();
    }

    public void sendtomyserver(View v){

    }

    public void stop(View view){
        // playRecord.setVisibility(View.VISIBLE);
        sendServer.setVisibility(View.VISIBLE);
        myAudioRecorder.stop();
        myAudioRecorder.release();
        myAudioRecorder  = null;
        stopRecord.setEnabled(false);
        playRecord.setEnabled(true);
        Toast.makeText(getApplicationContext(), "Audio recorded successfully",
                Toast.LENGTH_LONG).show();
        isRunning = false;
    }

    public void play(View view) throws IllegalArgumentException,
            SecurityException, IllegalStateException, IOException{
        MediaPlayer m = new MediaPlayer();
        m.setDataSource(outputFile);
        m.prepare();
        m.start();
        playRecord.setEnabled(false);
        startRecord.setEnabled(true);
        Toast.makeText(getApplicationContext(), outputFile, Toast.LENGTH_SHORT).show();
    }

    public void startTimer(){
        new Thread (new Runnable() {
            @Override
            public void run() {
                try{
                    Thread.sleep(5000);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run()
                        {
                            doFinish();
                        }
                    });
                }
            }
        }).start();
    }

    private synchronized void doFinish()
    {
        if (isRunning)
        {
            isRunning = false;
            Toast.makeText(getApplicationContext(), "Your time is over!", Toast.LENGTH_SHORT).show();

            // sendServer.setVisibility(View.VISIBLE);
            // relativeLayout3.setVisibility(View.VISIBLE);
            // finish();
        }
    }

    ///////////////////////////////////
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.record, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public void onClick(View v) {
        if(R.id.dialogSendButton == v.getId()) {
            sendtomyserver(v);
        }
    }
}